package com.selectable;

import javax.swing.*;
import javax.swing.border.LineBorder;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.util.ArrayList;

public class XPanel extends JPanel implements Pickable{
    private ArrayList<Item> items = new ArrayList<>();
    private Point p;
    private Point p2;
    private final JPanel paint = new JPanel();
    public XPanel(){
        super();
        paint.setBackground(new Color(0xab,0xcd,0xef,0x55));
        paint.setBounds(0,0,0,0);
        paint.setBorder(new LineBorder(Color.BLACK));
        add(paint);
        addMouseMotionListener(new MouseMotionAdapter() {
            @Override
            public void mouseDragged(MouseEvent e) {
                super.mouseDragged(e);
                p2 = e.getPoint();
                if(p != null){
                    int x1 = (int) p.getX();
                    int y1 = (int) p.getY();
                    int x2 = (int) p2.getX();
                    int y2 = (int) p2.getY();
                    int x = (int) Math.abs(p2.getX()-p.getX());
                    int y = (int) Math.abs(p2.getY()-p.getY());
                    int px,py;
                    px = Math.min(x2, x1);
                    py = Math.min(y2, y1);
                    getPaint().setBounds(px,py,x,y);
                    XPanel.this.setChildItemSelected();
                    XPanel.this.repaint();
                }
            }

            @Override
            public void mouseMoved(MouseEvent e) {
                super.mouseMoved(e);
            }
        });
        setLayout(null);
        for(int i = 0;i<12;i++){
            Item j = new Item("hello");
            j.setBounds((i%6)*100,(i/6)*40,100,40);
            add(j);
        }
        this.addMouseListener(this);
    }
    @Override
    public Component add(Component component){
        if(component instanceof Item){
            super.add(component);
            this.items.add((Item)component);
        }else{
            super.add(component);
        }
        return component;
    }
    @Override
    public JPanel getPaint() {
        return this.paint;
    }
    public void setChildItemSelected(boolean bv) {
        for(Item item:items){
            item.setSelect(bv);
        }
    }
    @Override
    public void setChildItemSelected() {
        for(Item item:items){
            Rectangle r1 = item.getBounds();
            item.setSelect(overlapping(r1));
//            System.out.println(items.size());
        }
    }
    @Override
    public void mouseClicked(MouseEvent e) {

    }

    @Override
    public void mousePressed(MouseEvent e) {
        p = e.getPoint();
        System.out.println("Click Listener PRESS"+p);
    }

    @Override
    public void mouseReleased(MouseEvent e) {
        p = null;
        p2 = null;
        getPaint().setBounds(0,0,0,0);
        this.repaint();
        this.setChildItemSelected(false);
    }




}
